﻿ using System;
using System.Collections.Generic;
using System.Linq;

namespace Medianamik.UI.Web.Shop.BuyingProcess
{
    public interface IBuyingProcessService
    {
        IList<BuyingProcessDto> GetBuyingProcessSteps(Guid currentPageNodeId, Guid currentStep);
        IList<BuyingProcessDto> GetBuyingProcessSteps();
        bool StepIsDone(Guid nodeId);
        string GetNextPageUrl(Guid nodeId);
        bool IsLastPage(Guid nodeId);
    }

    public abstract class BuyingProcessService : IBuyingProcessService
    {
        protected abstract IList<BuyingProcessDto> BuyingProcessSteps { get; }

        public virtual IList<BuyingProcessDto> GetBuyingProcessSteps()
        {
            return BuyingProcessSteps;
        }

        public virtual IList<BuyingProcessDto> GetBuyingProcessSteps(Guid currentPageNodeId, Guid currentStep)
        {
            var stepIsDone = currentStep != Guid.Empty;
            var isLastStep = IsLastPage(currentPageNodeId);
            foreach (var buyingProcessStep in BuyingProcessSteps)
            {
                buyingProcessStep.IsCurrentStep = buyingProcessStep.NodeId == currentPageNodeId;
                buyingProcessStep.StepIsDone = stepIsDone;
                buyingProcessStep.IsClikable = stepIsDone && !isLastStep;

                if (buyingProcessStep.NodeId == currentStep)
                    stepIsDone = false;
            }
            return BuyingProcessSteps;
        }

        public virtual bool StepIsDone(Guid nodeId)
        {
            return (from buyingProcessStep in BuyingProcessSteps
                    where buyingProcessStep.NodeId == nodeId
                    select buyingProcessStep.StepIsDone).FirstOrDefault();
        }

        public virtual bool IsLastPage(Guid nodeId)
        {
            for (var i = 0; i < BuyingProcessSteps.Count; i++)
            {
                if (BuyingProcessSteps[i].NodeId == nodeId)
                    return (i + 1) == BuyingProcessSteps.Count;
            }
            return true;
        }

        public virtual string GetNextPageUrl(Guid nodeId)
        {
            if (!IsLastPage((nodeId)))
            {
                for (var i = 0; i < BuyingProcessSteps.Count; i++)
                {
                    if (BuyingProcessSteps[i].NodeId == nodeId)
                        return (i + 1) < BuyingProcessSteps.Count ? BuyingProcessSteps[i + 1].Url : "";
                }
            }
            return "";
        }
    }
}
